package cn.six1943.deepchat.module.ai.controller.admin.chatsession;

import cn.hutool.core.util.IdUtil;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.six1943.deepchat.module.ai.util.SseUtil;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.constraints.*;
import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.six1943.deepchat.module.ai.controller.admin.chatsession.vo.*;
import cn.six1943.deepchat.module.ai.dal.dataobject.chatsession.ChatSessionDO;
import cn.six1943.deepchat.module.ai.dal.dataobject.chatsession.ChatMsgDO;
import cn.six1943.deepchat.module.ai.service.chatsession.ChatSessionService;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@Tag(name = "管理后台 - 会话")
@RestController
@RequestMapping("/app/ai/chat-session")
@Validated
public class ChatSessionController {

    @Resource
    private ChatSessionService chatSessionService;

    @PostMapping("/create")
    @Operation(summary = "创建会话")
    @PreAuthorize("@ss.hasPermission('ai:chat-session:create')")
    public CommonResult<Long> createChatSession(@Valid @RequestBody ChatSessionSaveReqVO createReqVO) {
        return success(chatSessionService.createChatSession(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新会话")
    @PreAuthorize("@ss.hasPermission('ai:chat-session:update')")
    public CommonResult<Boolean> updateChatSession(@Valid @RequestBody ChatSessionSaveReqVO updateReqVO) {
        chatSessionService.updateChatSession(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除会话")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('ai:chat-session:delete')")
    public CommonResult<Boolean> deleteChatSession(@RequestParam("id") Long id) {
        chatSessionService.deleteChatSession(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除会话")
                @PreAuthorize("@ss.hasPermission('ai:chat-session:delete')")
    public CommonResult<Boolean> deleteChatSessionList(@RequestParam("ids") List<Long> ids) {
        chatSessionService.deleteChatSessionListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得会话")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('ai:chat-session:query')")
    public CommonResult<ChatSessionRespVO> getChatSession(@RequestParam("id") Long id) {
        ChatSessionDO chatSession = chatSessionService.getChatSession(id);
        return success(BeanUtils.toBean(chatSession, ChatSessionRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得会话分页")
    @PreAuthorize("@ss.hasPermission('ai:chat-session:query')")
    public CommonResult<PageResult<ChatSessionRespVO>> getChatSessionPage(@Valid ChatSessionPageReqVO pageReqVO) {
        PageResult<ChatSessionDO> pageResult = chatSessionService.getChatSessionPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ChatSessionRespVO.class));
    }

    @GetMapping("/list")
    @Operation(summary = "获得会话列表")
    @PreAuthorize("@ss.hasPermission('ai:chat-session:list')")
    public CommonResult<List<ChatSessionRespVO>> getChatSessionList(@Valid ChatSessionPageReqVO pageReqVO) {
        List<ChatSessionDO> pageResult = chatSessionService.getChatSessionList(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ChatSessionRespVO.class));
    }

    // ==================== 子表（会话消息） ====================

    @GetMapping("/msg/page")
    @Operation(summary = "获得会话消息分页")
    @Parameter(name = "sessionId", description = "会话id")
    @PreAuthorize("@ss.hasPermission('ai:chat-session:query')")
    public CommonResult<PageResult<ChatMsgDO>> getChatMsgPage(PageParam pageReqVO, @RequestParam("sessionId") Long sessionId) {
        return success(chatSessionService.getChatMsgPage(pageReqVO, sessionId));
    }

    @PostMapping("/msg/create")
    @Operation(summary = "创建会话消息")
    @PreAuthorize("@ss.hasPermission('ai:chat-session:create')")
    public CommonResult<Long> createChatMsg(@Valid @RequestBody ChatMsgDO chatMsg) {
        return success(chatSessionService.createChatMsg(chatMsg));
    }

    @PutMapping("/msg/update")
    @Operation(summary = "更新会话消息")
    @PreAuthorize("@ss.hasPermission('ai:chat-session:update')")
    public CommonResult<Boolean> updateChatMsg(@Valid @RequestBody ChatMsgDO chatMsg) {
        chatSessionService.updateChatMsg(chatMsg);
        return success(true);
    }

    @DeleteMapping("/msg/delete")
    @Parameter(name = "id", description = "编号", required = true)
    @Operation(summary = "删除会话消息")
    @PreAuthorize("@ss.hasPermission('ai:chat-session:delete')")
    public CommonResult<Boolean> deleteChatMsg(@RequestParam("id") Long id) {
        chatSessionService.deleteChatMsg(id);
        return success(true);
    }

    @DeleteMapping("/msg/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除会话消息")
    @PreAuthorize("@ss.hasPermission('ai:chat-session:delete')")
    public CommonResult<Boolean> deleteChatMsgList(@RequestParam("ids") List<Long> ids) {
        chatSessionService.deleteChatMsgListByIds(ids);
        return success(true);
    }

	@GetMapping("/msg/get")
	@Operation(summary = "获得会话消息")
	@Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('ai:chat-session:query')")
	public CommonResult<ChatMsgDO> getChatMsg(@RequestParam("id") Long id) {
	    return success(chatSessionService.getChatMsg(id));
	}

    /**
     * sse问答接口
     */
    @PostMapping("/{id}/chat")
    @Operation(summary = "sse方式对话", description = "流式回答")
    // @ULog(moduleName = "AI", typeName = "机器人问答")
    public SseEmitter chatBySse(@PathVariable("id") Long id, @RequestBody ChatRequest req, HttpServletResponse response) {
        response.setHeader("X-Accel-Buffering", "no");
        response.setHeader("Content-Type", "text/event-stream");
        req.setTenantId(SecurityFrameworkUtils.getLoginUser().getTenantId()+"");
        req.setUserId(SecurityFrameworkUtils.getLoginUserId());
        req.setSessionId(id);
        SseEmitter emitter = null;
        emitter = chatSessionService.sseChat(req);
        // SseEmitter emitter = SseUtil.getConn("dfslkdjfs");
        // for (int i = 0; i < 10; i++) {
        //
        //     try {
        //         MsgChunkVO chunk = MsgChunkVO.builder()
        //                 .model("ddd")
        //                 .id(IdUtil.fastUUID())
        //                 .choices(List.of(MsgChoiceVO.builder().role("sdf").content(IdUtil.objectId()).build()))
        //                 .build();
        //         emitter.send(chunk);
        //         Thread.sleep(1000);
        //     } catch (Exception e) {
        //         throw new RuntimeException(e);
        //     }
        // }
        // emitter.complete();
        return emitter;
    }
}